package com.wxw.BaseLibrary.net;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Build;
import android.os.IBinder;
import com.pusys.bean.Constants;

/**
 * Created by david on 2019-02-14.
 */
public class NetworkService extends Service {
    private static long start_time = 0L;
    private static long end_time = 0L;
    private static long l_start = 0L;
    private static long l_end = 0L;
    public static boolean isMonitor;
//    public static TcpClient tcpClient;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        if (tcpClient == null) return;
        monitorNetworkStatus(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AsyncClient.getInstance().disConnect();
//        if (tcpClient != null) {
//            tcpClient.stop();
//            tcpClient = null;
//        }
    }

    public void monitorNetworkStatus(Context context) {
        if (isMonitor) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm != null) {
                isMonitor = true;
                cm.requestNetwork(new NetworkRequest.Builder().build(), new ConnectivityManager.NetworkCallback(){
                    @Override
                    public void onAvailable(Network network) {
                        super.onAvailable(network);
                        end_time = System.currentTimeMillis();
                        if (end_time-start_time>1000) {
                            start_time = end_time;
                            if (!AsyncClient.getInstance().connect()) {

                            }
//                            tcpClient.showReceiveMsg("Network onAvailable", Constants.SYSTEM_MSG.getCode());
//                            tcpClient.start();
                        }
                    }

                    @Override
                    public void onLost(Network network) {
                        super.onLost(network);
                        l_end = System.currentTimeMillis();
                        if (l_end-l_start>1000) {
                            AsyncClient.getInstance().disConnect();
//                            tcpClient.showReceiveMsg("Network onLost",Constants.SYSTEM_MSG.getCode());
//                            tcpClient.stop();
                            l_start = l_end;
                        }
                    }
                });
            }
        }
    }
}
